import pyautogui as pag
import cv2
import numpy as np
import time
import os
import pynput
import keyboard
from threading import Thread  # 创建线程的模块
from ctypes import *
import img_ocr



#im = pyautogui.screenshot()#截取整个屏幕
#om = im.crop((1127, 756, 1146, 775))#根据截取的屏幕仅截取“带赞的手势图片”，用pyautogui.mouseInfo()获取图片的位置(1127,756,1146,775)，这里截取区域用到了Pillow
#om.save(r"C:\Users\hanbo\Desktop\demo\dianzan.png")#将图片保存供pyautogui.locateOnScreen（）使用

#im.save('C:\\Users\\hanbo\\Desktop\\demo\\22.png')

run_flag = True
run_max_count = 10000


opt_dstwin_xy=None
opt_dstwin_wh=None
def setwinPos(x, y, w, h):
    global opt_dstwin_xy
    global opt_dstwin_wh
    opt_dstwin_xy=(x,y)
    opt_dstwin_wh=(w,h)

def keyborad_f1():
    print('ctrl+alt+x')
    global run_flag
    run_flag = False

def keyborad_thread():
    print("keyborad_thread start")
    keyboard.add_hotkey('ctrl+alt+x', keyborad_f1)
    keyboard.wait('ctrl+alt+x')
    print("keyborad_thread end")

def click_ocr_opt():
    global opt_dstwin_xy
    global opt_dstwin_wh
    if(opt_dstwin_xy is None):
        opt_dstwin_xy = (0,0)
        opt_dstwin_wh = pag.size()
    im = pag.screenshot(region=(opt_dstwin_xy[0],opt_dstwin_xy[1], opt_dstwin_wh[0] ,opt_dstwin_wh[1]))
    # 保存图片
    cvimg = cv2.cvtColor(np.array(im),cv2.COLOR_RGB2BGR)
    #cv2.imshow("pp",cvimg)
    #cv2.waitKey()
    #cv2.destroyAllWindows()
    img_ocr.recoText(cvimg)

def select_btn_ok():
    #选择正确按钮
    posxy = pag.locateOnScreen(r"result_btn.png",confidence=0.8,grayscale=True)
    if(posxy):
        print("result_btn,",posxy)
        center = pag.center(posxy)  # 寻找图片的中心
        pag.click(center)

def select_btn_commit():
    #选择提交按钮
    posxy = pag.locateOnScreen(r"commit_btn.png",confidence=0.7)
    if(posxy):
        print("result_btn,",posxy)
        center = pag.center(posxy)  # 寻找图片的中心
        pag.click(center)
def select_btn_next():
    #选择提交按钮
    posxy = pag.locateOnScreen(r"next_btn.png",confidence=0.95,grayscale=True)
    if(posxy):
        print("result_btn,",posxy)
        center = pag.center(posxy)  # 寻找图片的中心
        pag.click(center)

def  click_opt():
    global run_flag
    global run_max_count
    global opt_dstwin_xy
    global opt_dstwin_wh

    time.sleep(1)

    p = Thread(target=keyborad_thread,daemon=True)
    p.start()

    print("'ctrl+alt+x' stop")

    maxcount = run_max_count
    while run_flag:        
        #获取保存图片的坐标
        print("remaincount:{},maxcount:{}".format(run_max_count,maxcount))
        time.sleep(1)
        posxy = pag.locateOnScreen(r"result_btn.png",confidence=0.8,grayscale=True)
        if(posxy):
            print("result_btn,",posxy)
            center = pag.center(posxy)  # 寻找图片的中心
            pag.click(center)

            #time.sleep(1)
            posxy = pag.locateOnScreen(r"commit_btn.png",confidence=0.7)
            if(posxy):
                print("commit_btn,",posxy)
                center = pag.center(posxy)  # 寻找图片的中心
                pag.click(center)
            else:
                print("commit_btn find error")
        else:
            print("result_btn find error")


        time.sleep(2)
        posxy = pag.locateOnScreen(r"next_btn.png",confidence=0.95,grayscale=True)
        if(posxy):
            print("next_btn,",posxy)
            center = pag.center(posxy)  # 寻找图片的中心
            pag.click(center)
        else:
            print("next_btn find error")
        
        run_max_count = run_max_count -1
        if(run_max_count <= 0):
            time.sleep(1)
            #自动锁屏
            user32 = windll.LoadLibrary('user32.dll')
            user32.LockWorkStation()
            run_flag = False

    print("click_opt exit:run count:",run_max_count)

def  click_opt_opencv_localeOnImg(_dstImg):
    #使用opencv的好处是可以缩放图片
    screenScale=1 #缩放比例

    #使用opencv定位图片位置
    im = pag.screenshot()#截取整个屏幕
    #tempimg = cv2.cvtColor(np.array(im),cv2.COLOR_RGB2GRAY)
    #dstimg = cv2.imread(_dstImg,cv2.IMREAD_GRAYSCALE)
    tempimg = cv2.cvtColor(np.array(im),cv2.COLOR_RGB2BGR)
    dstimg = cv2.imread(_dstImg)

    theight, twidth = dstimg.shape[:2]
    tempheight, tempwidth = tempimg.shape[:2]
    print("目标图宽高："+str(twidth)+"-"+str(theight))
    print("模板图宽高："+str(tempwidth)+"-"+str(tempheight))
        
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp=cv2.resize(tempimg, (int(tempwidth * screenScale), int(tempheight * screenScale)))
    scaleDst = cv2.resize(dstimg,(int(twidth * screenScale), int(theight * screenScale)))
    stempheight, stempwidth = scaleTemp.shape[:2]
    print("缩放后模板图宽高："+str(stempwidth)+"-"+str(stempheight))

    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, scaleDst, cv2.TM_CCOEFF_NORMED)
    mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if(max_val>=0.5):
        # 计算出中心点
        # top_left = max_loc
        # bottom_right = (top_left[0] + twidth, top_left[1] + theight)
        # tagHalfW=int(twidth/2)
        # tagHalfH=int(theight/2)
        # tagCenterX=top_left[0]+tagHalfW
        # tagCenterY=top_left[1]+tagHalfH
        #左键点击屏幕上的这个位置
        #pag.click(tagCenterX,tagCenterY,button='left')
        return (int(max_loc[0]/screenScale),int(max_loc[1]/screenScale),twidth,theight)
    print ("没找到")
    return ()

    pass
def  click_opt_opencv():
    global run_flag
    global run_max_count
    global opt_dstwin_xy
    global opt_dstwin_wh

    time.sleep(1)

    p = Thread(target=keyborad_thread,daemon=True)
    p.start()

    print("'F1' stop")

    while run_flag:        
        #获取保存图片的坐标
        time.sleep(3)
        posxy = pag.locateOnScreen(r"result_btn.png",confidence=0.8,grayscale=True)
        if(posxy):
            print("result_btn,",posxy)
            center = pag.center(posxy)  # 寻找图片的中心
            pag.click(center)

            #time.sleep(1)
            posxy = pag.locateOnScreen(r"commit_btn.png",confidence=0.7)
            if(posxy):
                print("commit_btn,",posxy)
                center = pag.center(posxy)  # 寻找图片的中心
                pag.click(center)
            else:
                print("commit_btn find error")
        else:
            print("result_btn find error")


        time.sleep(2)
        posxy = pag.locateOnScreen(r"next_btn.png",confidence=0.95,grayscale=True)
        if(posxy):
            print("next_btn,",posxy)
            center = pag.center(posxy)  # 寻找图片的中心
            pag.click(center)
        else:
            print("next_btn find error")
        
        run_max_count = run_max_count -1
        if(run_max_count <= 0):
            time.sleep(1)
            #自动锁屏
            user32 = windll.LoadLibrary('user32.dll')
            user32.LockWorkStation()
            run_flag = False

    print("click_opt exit:run count:",run_max_count)

# while True:
#         print("Press Ctrl-C to end")
#         screenWidth, screenHeight = pag.size()  #获取屏幕的尺寸
#         print(screenWidth,screenHeight)
#         x,y = pag.position()   #获取当前鼠标的位置
#         posStr = "Position:" + str(x).rjust(4)+','+str(y).rjust(4)
#         print(posStr)
#         time.sleep(1)
#         #os.system('cls')   #清楚屏幕

import cv2

if __name__ == '__main__':
    #click_opt()
    
    # 加载主图片和子图片
    img = cv2.imread('tf_question.png')
    template = cv2.imread('test_next.png')

    # 获取子图片的尺寸
    h, w = template.shape[:2]

    # 在主图片中查找子图片
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)

    # 获取匹配结果的坐标
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    # 在主图片上绘制匹配结果的框
    top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2)

    # 将结果显示出来
    cv2.imshow('Result', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    